package com.lwt.service.impl;

import com.lwt.mapper.MessageMapper;
import com.lwt.po.Message;
import com.lwt.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: blog
 * @author: 关键我是大怪
 * @create: 2021-08-03 15:47
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    //存放迭代找出的所有子代的集合
    private List<Message> tempReplys = new ArrayList<>();

    @Override
    public List<Message> listMessage() {
        //查询出父节点
        List<Message> messages = messageMapper.findMessage(Long.parseLong("-1"));
        for (Message message : messages) {
            Long id = message.getId();
            String parentNickname1 = message.getNickname();
            List<Message> childMessage = messageMapper.findMessage(id);
            //查询出子留言
            combineChildren(childMessage, parentNickname1);
            message.setReplyMessages(tempReplys);
            tempReplys = new ArrayList<>();

        }


        return messages;
    }

    private void combineChildren(List<Message> childMessages, String parentNickname1) {
        //判断是否有一级子回复
        if (childMessages.size() > 0) {
            //循环找出子留言的id
            for (Message childMessage : childMessages) {
                String parentNickname = childMessage.getNickname();
                childMessage.setParentNickname(parentNickname1);
                tempReplys.add(childMessage);
                Long childId = childMessage.getId();
                List<Message> replayMessages = messageMapper.findMessage(childId);
                //查询二级以及所有子集回复
                combineChildren(replayMessages, parentNickname);
            }
        }
    }

    @Override
    public int saveMessage(Message message) {
        message.setCreateTime(new Date());
        return messageMapper.saveMessage(message);
    }

    @Override
    public void deleteMessage(Long id) {
        deletechild(id);
        messageMapper.deleteMessage(id);
    }

    //删除子评论
    private void deletechild(Long id) {
        List<Message> messages = messageMapper.findMessage(id);
        if (messages.size() > 0) {
            for (Message message : messages) {
                Long id1 = message.getId();
                deletechild(id1);
                messageMapper.deleteMessage(id1);
            }
        }
    }
}
